'use strict';

const {
	rejects
} = require("assert");
const {
	resolve
} = require("dns");

exports.main = async (event, context) => {
	const db = uniCloud.database()
	const collection = db.collection('AccountBook')
	const aggregate = collection.aggregate()
	const $ = db.command.aggregate
	let res = await aggregate.group({
		"_id": "$strDate",
		"Arr": $.push({
			"OptionNote": "$OptionNote",
			"OptionType": "$OptionType",
			"OptionTypeicon": "$OptionTypeicon",
			"intCount": "$intCount",
			"topOption": "$topOption"
		}),
		"IncomeTotal": $.sum($.multiply([$.abs($.subtract(['$topOption', 1])), "$intCount"])),
		"ExpenseTotal": $.sum($.multiply([$.abs($.subtract(['$topOption', 0])), "$intCount"]))
	}).sort({
		"_id": -1
	}).end()
	const aggregate2 = collection.aggregate()
	const $2 = db.command.aggregate2
	let Total = await aggregate2.group({
		"_id": "$topOption",
		"AllExpenseTotal": $.sum($.multiply([$.abs($.subtract(["$topOption", 0])), '$intCount'])),
		"AllIncomeTotal": $.sum($.multiply([$.abs($.subtract(['$topOption', 1])), "$intCount"])),
	}).end()
	let AllTotal = {
		AllIncomeTotal: 0,
		AllExpenseTotal: 0
	}
	Total.data.forEach((item, index) => {
		if (item._id == 0) {
			AllTotal.AllIncomeTotal = item.AllIncomeTotal
		} else {
			AllTotal.AllExpenseTotal = item.AllExpenseTotal
		}
	})
	return {res,AllTotal}
};